package com.loveprogrammer.oss.common.uploader;


import com.aliyun.oss.common.utils.StringUtils;
import com.loveprogrammer.oss.common.uploader.constant.FileType;

import java.time.LocalDateTime;
import java.util.Objects;

public class TimeStampPathBuilder implements UploadPathBuilder {

    private String path;
    private String fileName;
    private FileType fileType;

    public TimeStampPathBuilder() {
    }

    /**
     *
     * 上传路径 builder
     *
     * @param path     路径
     * @param fileName 文件名
     * @param fileType 文件拓展名
     * @return key
     */
    public TimeStampPathBuilder(String path, String fileName, FileType fileType) {
        this.path = path;
        this.fileName = fileName;
        this.fileType = fileType;
    }

    public TimeStampPathBuilder path(String path) {
        return this;
    }

    public TimeStampPathBuilder fileName(String fileName) {
        return this;
    }

    public TimeStampPathBuilder fileType(FileType fileType) {
        return this;
    }

    @Override
    public String build() {

        if (Objects.isNull(fileType)) {
            fileType = FileType.txt;
        }
        LocalDateTime localDateTime = LocalDateTime.now();
        String year = localDateTime.getYear() + "";
        String month = localDateTime.getMonthValue() + "";
        if (month.length() < 2) {
            month = "0" + month;
        }
        String day = localDateTime.getDayOfMonth() + "";
        if (day.length() < 2) {
            day = "0" + day;
        }
        String hour = localDateTime.getHour() + "";
        if (hour.length() < 2) {
            hour = "0" + hour;
        }
        String minute = localDateTime.getMinute() + "";
        if (minute.length() < 2) {
            minute = "0" + minute;
        }
        String second = localDateTime.getSecond() + "";
        if (second.length() < 2) {
            second = "0" + second;
        }
        String millisecond = localDateTime.getNano() / 1000000 + "";

        StringBuilder uploadPath = new StringBuilder();

        uploadPath.append("/");
        if (!StringUtils.isNullOrEmpty(path)) {
            uploadPath.append(path).append("/");
        }

        //以时间戳对文件进行重命名，以免文件冲突
        uploadPath.append(year).append("_").append(month).append("_").append(day)
                .append("/").append(hour).append("_").append(minute).append("_").append(second).append("_").append(millisecond);

        if (!StringUtils.isNullOrEmpty(fileName)) {
            uploadPath.append("_").append(fileName).append(fileType.type).toString();
        }

        return uploadPath.toString();
    }

}
